<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="78px"
    >
      <el-form-item label="商品搜索:" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:sku:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:sku:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:sku:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:sku:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['manage:sku:add']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="skuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80px" />
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column
        label="商品图片"
        align="center"
        prop="skuImage"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.skuImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="规格" align="center" prop="unit" />
      <el-table-column label="商品价格" align="center" prop="price">
        <template #default="scope">
          <el-tag>￥{{ (scope.row.price / 100).toFixed(2) }} 元</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="classId">
        <template #default="scope">
          <div v-for="s in skuTypeList" :key="s.classId">
            <span v-if="scope.row.classId == s.classId">{{ s.className }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="创建日期"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:sku:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:sku:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="skuRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="商品名称:" prop="skuName">
          <el-input v-model="form.skuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="品牌:" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="商品价格:" prop="price">
          <div style="display: flex">
            <el-input-number
              v-model="form.price"
              :min="0.01"
              :max="999.99"
              :precision="2"
              :step="0.5"
              placeholder="请输入商品价格"
              style="width: 200px"
            />
            &nbsp;&nbsp;
            <span>元</span>
          </div>
        </el-form-item>
        <el-form-item label="商品类型:" prop="classId">
          <!-- <el-input v-model="form.classId" placeholder="请输入商品类型" /> -->
          <el-select v-model="form.classId" placeholder="请选择商品类型">
            <el-option
              v-for="item in skuTypeList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格:" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="商品图片:" prop="skuImage">
          <image-upload v-model="form.skuImage" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 数据导入对话框 -->
    <el-dialog
      v-model="excelOpen"
      title="数据导入"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :auto-upload="false"
        :limit="1"
      >
        <template #trigger>
          <el-button type="primary">上传文件</el-button>
        </template>

        <el-button class="ml-3" type="success" @click="submitUpload">
          上传
        </el-button>

        <template #tip>
          <div class="el-upload__tip">
            上传文件仅支持，xls/xlsx格式，文件大小不得超过1M
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="sku">
import { listsku, getsku, delsku, addsku, updatesku } from "@/api/manage/sku";
import { loadAllParam } from "@/api/page";
import { listskuType } from "@/api/manage/skuType";
import { showDeleteErrorNotification } from "@/utils/errorHandler";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const skuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const skuNames = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    skuName: null,
    brandName: null,
    price: null,
    classId: null,
    isDiscount: null,
  },
  rules: {
    skuName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
      // 支持中文、英文、数字
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
        message: "请输入中文、英文、数字",
        trigger: "blur",
      },
    ],
    skuImage: [
      { required: true, message: "商品图片不能为空", trigger: "blur" },
    ],
    brandName: [
      { required: true, message: "品牌不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
    ],
    unit: [
      { required: true, message: "规格不能为空", trigger: "blur" },
      // 只支持数字、英文
      {
        pattern: /^[a-zA-Z0-9]+$/,
        message: "只支持数字、英文",
        trigger: "blur",
      },
    ],
    price: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
    classId: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品管理列表 */
function getList() {
  loading.value = true;
  listsku(queryParams.value).then((response) => {
    skuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    skuId: null,
    skuName: null,
    skuImage: null,
    brandName: null,
    unit: null,
    price: null,
    classId: null,
    isDiscount: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("skuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.skuId);
  skuNames.value = selection.map((item) => item.skuName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _skuId = row.skuId || ids.value;
  getsku(_skuId).then((response) => {
    form.value = response.data;
    // 将价格从分转换为元，用于界面显示（数据库存储为分单位）
    form.value.price /= 100;
    open.value = true;
    title.value = "修改商品管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["skuRef"].validate((valid) => {
    if (valid) {
      // 创建提交数据的深拷贝，避免直接修改form数据
      const submitData = { ...form.value };
      // 将价格单位从元转换为分存储
      submitData.price *= 100;

      if (form.value.skuId != null) {
        updatesku(submitData)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            // 关闭对话框
            open.value = false;
            // 刷新列表数据
            getList();
          })
          .catch(() => {
            // 请求失败时不需要恢复价格，因为form.value.price没有被修改
            proxy.$modal.msgError("修改失败");
          });
      } else {
        addsku(submitData)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            // 关闭对话框
            open.value = false;
            // 刷新列表数据
            getList();
          })
          .catch(() => {
            // 请求失败时不需要恢复价格，因为form.value.price没有被修改
            proxy.$modal.msgError("新增失败");
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _skuIds = row.skuId || ids.value;
  const _skuNames = row.skuName || skuNames.value;
  proxy.$modal
    .confirm('是否确认删除商品管理名称为"' + _skuNames + '"的数据项？')
    .then(function () {
      return delsku(_skuIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      const cancelTokens = ["cancel", "close"];
      const normalize = (value) =>
        typeof value === "string" ? value.trim().toLowerCase() : "";

      if (
        cancelTokens.includes(normalize(error)) ||
        cancelTokens.includes(normalize(error?.msg)) ||
        cancelTokens.includes(normalize(error?.message))
      ) {
        return;
      }

      // 使用自定义错误处理，支持换行显示
      const message =
        error?.msg ||
        error?.message ||
        (typeof error === "string" ? error : "") ||
        "删除失败";

      showDeleteErrorNotification(message, {
        footer: "如需强制删除，请先解除设备与商品的绑定关系。"
      });
    });
}
/** 导出按钮操作 */
function handleExport() {
  // 检查是否有选中的商品
  if (ids.value && ids.value.length > 0) {
    // 导出选中的商品
    proxy.$modal.confirm('是否确认导出选中的 ' + ids.value.length + ' 个商品数据项？')
      .then(() => {
        // 手动构建查询字符串，支持多个同名参数
        const queryString = ids.value.map(id => `skuIds=${id}`).join('&');
        console.log("构建的查询字符串:", queryString);
        console.log("选中的ids:", ids.value);
        
        // 使用查询字符串方式调用
        const downloadUrl = `manage/sku/export?${queryString}`;
        proxy.download(
          downloadUrl,
          {},  // 空参数对象
          `sku_selected_${new Date().getTime()}.xlsx`
        );
      })
      .catch(() => {});
  } else {
    // 没有选中商品，询问是否导出全部
    proxy.$modal.confirm('未选择任何商品，是否导出当前查询条件下的全部商品数据？')
      .then(() => {
        proxy.download(
          "manage/sku/export",
          {
            ...queryParams.value,
          },
          `sku_all_${new Date().getTime()}.xlsx`
        );
      })
      .catch(() => {});
  }
}
// 打开数据导入对话框
const excelOpen = ref(false);
function handleImport() {
  excelOpen.value = true;
}
// 上传excel文件
const uploadRef = ref({});
function submitUpload() {
  uploadRef.value.submit();
}
// 上传地址
const uploadExcelUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/manage/sku/import"
);
// 上传请求头
const headers = ref({ Authorization: "Bearer " + getToken() });

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("上传excel成功");
    excelOpen.value = false;
    getList();
  } else {
    proxy.$modal.msgError(res.msg);
  }
  // 清空上传文件清单
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}
// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传excel失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}
// 上传前校验
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如['xls', 'xlsx']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },

});
// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } 
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传excel大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传excel，请稍候...");
}

// 查询所有类型
const skuTypeList = ref([]);
function getskuList() {
  listskuType(loadAllParam).then((response) => {
    skuTypeList.value = response.rows;
  });
}

getskuList();

getList();
</script>
<style scoped>
/* Element Plus对话框标题样式 */
:deep(.el-dialog__title) {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}
</style>
